package cn.itcast.tanhua.sso.service;

import cn.itcast.tanhua.sso.config.AliyunSMSConfig;
import cn.itcast.tanhua.sso.vo.ErrorResult;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * @ClassName SmsService
 * @Description 发送短信验证码
 * @Author WU
 * @Date 2021/5/24 18:37
 * @Version 1.0
 */
@Service
@Slf4j
public class SmsService {
//    注入redisTemplate对象
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

//    注入获取配置参数的对象
    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    /**
    * @Description: 定义短息发送方法
    * @Param: 从外部传入手机号
    * @return:
    * @Author: Mr.Tan
    * @Date: 2021/5/24
    */
    public String sendSms(String phone){
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSMSConfig.getRegionId(), aliyunSMSConfig.getAccessKeyId(), aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

//        生成随机的6位数验证码
//        String code= RandomUtils.nextInt(100000,999999)+"";
        String code="132144";
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(aliyunSMSConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "ABC商城");
        request.putQueryParameter("TemplateCode", aliyunSMSConfig.getTemplateCode());
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
//            获取返回结果中的数据
            String data = response.getData();
//            如果数据中有"message:ok"，则说明发送成功，将验证码返回
            if (StringUtils.contains(data, "\"Message\":\"OK\"")) {
                return code;
            }
//            发送失败则记录日志
            log.info("发送短信验证码失败~ data = " + data);
        } catch (Exception e) {
//            捕捉到异常也记录日志
            log.error("发送短信验证码失败~ mobile = " + phone, e);
        }
//        没有发送成功要向controller层返回null
        return null;
    }

    
    /**
    * @Description: 发送短信验证码前核实是否该手机号刚发过验证码且在有效期
    * @Param: phone
    * @return: 
    * @Author: Mr.Tan
    * @Date: 2021/5/24
    */
    public ErrorResult sendCheckCode(String phone) {
        String redisKey = "CHECK_CODE_" + phone;
        //先判断该手机号发送的验证码是否还未失效
        if (this.redisTemplate.hasKey(redisKey)) {
//            未失效，编辑结果信息并返回
            String msg="上一次发送的验证码还未失效！";
            return ErrorResult.builder().errCode("000001").errMessage(msg).build();
        }

//        失效则重新发送短信
//        String code = this.sendSms(phone);
        String code = "123456";

//        返回结果为null则发送验证码失败
        if (StringUtils.isEmpty(code)) {
            String msg = "发送短信验证码失败！";
            return ErrorResult.builder().errCode("000000").errMessage(msg).build();
        }

        //短信发送成功，将验证码保存到redis中，设置有效期
        this.redisTemplate.opsForValue().set(redisKey,code, Duration.ofMinutes(5));
        return null;
    }
}
